<template>
  <div>
    <BasicTable @register="registerAssetTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="分配客户">
                  <a-button type="text" @click="handleSelectedAssign">
                    <Icon :icon="ICON.ASSIGN" color="#0960bd" />
                  </a-button>
                </Tooltip>
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar v-if="hasPermission(RoleEnum.TENANT_ADMIN)">
        <Dropdown
          :trigger="['click']"
          :dropMenuList="[
            {
              text: '添加资产',
              icon: ICON.ADDENTITY,
              event: '',
              onClick: () => {
                openAddModal(true, {});
              },
            },
            {
              text: '导入资产',
              icon: ICON.IMPORTENTITY,
              event: '',
              onClick: () => {
                openUploadModal(true, {});
              },
            },
          ]"
        >
          <a-button type="primary">添加资产</a-button>
        </Dropdown>
      </template>
      <template #bodyCell="{ column, record }" v-if="hasPermission(RoleEnum.TENANT_ADMIN)">
        <template v-if="column.key === 'action'">
          <TableAction
            :stopButtonPropagation="true"
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: openEditModal.bind(null, true, { record }),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '查看',
                  placement: 'top',
                },
                onClick: handleDetail.bind(null, record),
              },
              {
                icon: ICON.DELETE,
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :dropDownActions="[
              {
                icon: ICON.PUBLIC,
                label: '公开',
                disabled: record.customerIsPublic || record.customerTitle,
                onClick: handlePublic.bind(null, record),
              },
              {
                icon: ICON.ASSIGN,
                label: '分配给客户',
                disabled: record.customerTitle,
                onClick: openCustomerModal.bind(null, true, { record, key: 'customer' }),
              },
              {
                icon: ICON.UNASSIGN,
                label: '取消分配给客户',
                disabled: !record.customerTitle || record.customerIsPublic,
                onClick: handleCancel.bind(null, record),
              },
              {
                icon: ICON.PRIVATE,
                label: '私有',
                disabled: !record.customerIsPublic,
                onClick: handlePrivate.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!-- <AssetDrawer @register="registerDrawer" /> -->
    <PublicDrawer
      @register="registerDrawer"
      @update-desc-data="handleUpdateDescData"
      :show-tabs="
        hasPermission(RoleEnum.CUSTOMER_USER)
          ? ['detail', 'attribute', 'telemetry', 'alarm', 'event', 'association']
          : [
              'detail',
              'attribute',
              'telemetry',
              'alarm',
              'event',
              'association',
              'auditLogs',
              'version',
            ]
      "
    />
    <CustomerModal @register="registerCustomerModal" @success="handleSuccess" />
    <AddAssetModal @register="registerAddModal" @success="handleSuccess" />
    <UploadAssetModal @register="registerUploadModal" @success="handleSuccess" />
    <EditAssetModal @register="registerEditModal" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { assetTableSchema, searchSchema, detailSchema } from './asset.data';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { ICON } from '/@/enums/iconEnum';
  import Icon from '/@/components/Icon';
  import { useMessage } from '/@/hooks/web/useMessage';
  import AddAssetModal from './modal/AddAssetModal.vue';
  import { Dropdown } from '/@/components/Dropdown';
  import CustomerModal from './modal/CustomerModal.vue';
  import EditAssetModal from './modal/EditAssetModal.vue';
  import UploadAssetModal from './modal/UploadAssetModal.vue';
  import { ref, onMounted } from 'vue';
  import { Alert, Tooltip } from 'ant-design-vue';
  import { useRoute } from 'vue-router';
  import {
    getEntityAssetList,
    saveAsset,
    updateAsset,
    setAssetPublic,
    assignCustomer,
    unassignCustomer,
    deleteEntity,
    getEntityListByCustomerId,
    getAssetInfo,
    getEntityListByEdgeId,
    getCustomerEntityAssetList,
  } from '/@/api/thingsborad/entity/entity';
  import {
    entityTableParams,
    assetTableItem,
    saveAssetParams,
  } from '/@/api/thingsborad/entity/model/entityModel';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useUserStore } from '/@/store/modules/user';

  const { hasPermission } = usePermission();
  const userStore = useUserStore();
  const checkedKeys = ref<any>([]);

  const [registerAssetTable, { reload, setProps }] = useTable({
    title: '资产',
    columns: assetTableSchema,
    ...tableStyleSetting,
    afterFetch: (res) => {
      let list: assetTableItem[] = [];
      res.length != 0
        ? res.forEach((item: any) => {
            let tableItem: assetTableItem = {
              createdTime: item.createdTime,
              name: item.name,
              assetProfileName: item.assetProfileName,
              label: item.label,
              customerTitle: item.customerTitle,
              customerIsPublic: item.customerIsPublic,
              id: item.id.id,
              assetProfileId: item.assetProfileId,
              additionalInfo: item.additionalInfo,
            };
            list.push(tableItem);
          })
        : null;
      return list;
    },
    actionColumn: hasPermission(RoleEnum.TENANT_ADMIN) ? tableStyleSetting.actionColumn : null,
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },

    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 0 },
        lg: { span: 6, offset: 6 },
        xl: { span: 4, offset: 12 },
        xxl: { span: 4, offset: 12 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerCustomerModal, { openModal: openCustomerModal }] = useModal();
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const [registerUploadModal, { openModal: openUploadModal }] = useModal();
  const [registerEditModal, { openModal: openEditModal }] = useModal();
  const { createConfirm } = useMessage();

  // 公开
  function handlePublic(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将资产"${record.name}"设为公开吗？`,
      content: '确认后，资产及其所有数据将被公开并被他人访问。',
      onOk: async () => {
        await setAssetPublic(record.id);
        reload();
      },
    });
  }
  // 私有
  function handlePrivate(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将资产"${record.name}"设为私有吗？`,
      content: '确认后，资产及其所有数据将被私有化，无法被他人访问。',
      onOk: async () => {
        await unassignCustomer({ entityType: 'asset', id: record.id });
        reload();
      },
    });
  }
  // 取消分配
  function handleCancel(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要取消分配资产"${record.name}"吗？`,
      content: '确认后，资产将未分配，客户无法访问。',
      onOk: async () => {
        await unassignCustomer({ entityType: 'asset', id: record.id });
        reload();
      },
    });
  }
  // 删除
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除资产"${record.name}"吗？`,
      content: '请注意：确认后，资产及其所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteEntity({ entityType: 'asset', entityId: record.id });
        reload();
      },
    });
  }
  // 详情
  function handleDetail(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.ASSET,
      entityId: record.id,
      title: record.name,
      api: getAssetInfo,
      detailSchema: detailSchema,
      params: record.id,
    });
  }
  // 抽屉详情数据更改
  function handleUpdateDescData(value: Recordable) {
    value.name = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  }
  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选分配
  function handleSelectedAssign() {
    openCustomerModal(true, { checkedKeys, key: 'selected' });
  }
  // 多选删除
  function handleSelectedDelete() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个设备吗？`,
      content: '请注意：确认后，设备及其所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteEntity({ entityType: 'asset', entityId: item.id });
        }
        reload();
        checkedKeys.value = [];
      },
    });
  }

  async function handleSuccess(obj: any) {
    //更新保存 接口
    switch (obj.key) {
      case 'add':
        let saveAssetParams: saveAssetParams = {
          name: obj.values.name,
          assetProfileId: JSON.parse(obj.values.assetConfiguration),
          label: obj.values.label,
          customerId: obj.values.customer
            ? { entityType: 'CUSTOMER', id: obj.values.customer }
            : null,
          additionalInfo: {
            description: obj.values.remark,
          },
        };
        await saveAsset(saveAssetParams);
        reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
        break;
      case 'import':
        reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
        break;
      case 'edit':
        obj.record.assetProfileId =
          obj.values.assetConfiguration && JSON.parse(obj.values.assetConfiguration);
        obj.record.name = obj.values.name;
        obj.record.label = obj.values.label;
        obj.record.additionalInfo = {
          description: obj.values.remark,
        };
        await updateAsset(obj.record);
        reload();
        break;
      case 'selectedAssign':
        setProps({ loading: true });
        const promises = obj.values.checkedKeys.map((item) =>
          assignCustomer({
            customerId: obj.values.customerId,
            entityType: 'asset',
            entityId: item,
          }),
        );
        await Promise.all(promises);
        reload();
        checkedKeys.value = [];
        break;
      case 'assign':
        await assignCustomer({
          customerId: obj.values.customerId,
          entityType: 'asset',
          entityId: obj.values.assetId,
        });
        reload();
        break;
    }
  }

  function getParams(val: Recordable) {
    return {
      page: val.page - 1,
      pageSize: val.pageSize,
      sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
      sortProperty: val.field,
      textSearch: val.textSearch,
      assetProfileId: val.assetProfileId,
      active: val.state,
    };
  }

  onMounted(async () => {
    const route = useRoute();
    const roleList = userStore.getRoleList;
    const { customerId } = userStore.getUserInfo;
    if (roleList.includes(RoleEnum.TENANT_ADMIN)) {
      if (Boolean(route.params.key)) {
        switch (route.params.key) {
          case '客户':
            setProps({
              api: getEntityListByCustomerId,
              beforeFetch: (val) => {
                let params: entityTableParams & { customerId: any; infosType: string } = {
                  page: val.page - 1,
                  pageSize: val.pageSize,
                  sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
                  sortProperty: val.field,
                  customerId: route.params.id,
                  infosType: 'assetInfos',
                };
                val?.textSearch ? (params.textSearch = val.textSearch) : null;
                return params;
              },
              title: `${route.params.name}:资产`,
            });
            reload();
            break;
          case '边缘实例':
            setProps({
              api: getEntityListByEdgeId,
              beforeFetch: (val) => {
                let params: entityTableParams & { edgeId: any; infosType: string } = {
                  page: val.page - 1,
                  pageSize: val.pageSize,
                  sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
                  sortProperty: val.field,
                  edgeId: route.params.id,
                  infosType: 'assets',
                };
                val?.textSearch ? (params.textSearch = val.textSearch) : null;
                return params;
              },
              title: `${route.params.name}:资产`,
            });
            reload();
            break;
        }
      } else {
        setProps({
          api: getEntityAssetList,
          beforeFetch: (val: Recordable) => getParams(val),
        });
      }
    } else if (roleList.includes(RoleEnum.CUSTOMER_USER)) {
      setProps({
        api: getCustomerEntityAssetList,
        beforeFetch: (val) => {
          let params = {
            pagination: {
              page: val.page - 1,
              pageSize: val.pageSize,
              sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
              sortProperty: val.field,
              textSearch: val.textSearch,
              assetProfileId: val.assetProfileId,
            },
            customerId: customerId,
          };
          return params;
        },
      });
      reload();
    }
  });
</script>
